package org.anupta.game.server.game;

import org.anupta.game.main.Main;
import org.anupta.game.server.game.client.GameClient;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

public class GameHandler extends IoHandlerAdapter {
	@Override
    public void sessionOpened(IoSession session) throws Exception {
		Main.out.println(new StringBuilder("New connection : ").append(session.getRemoteAddress()).toString());
        session.setAttribute("client", new GameClient(session));
    }

    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {
        if (message == null) {
            return;
        }
        Main.out.println(message.toString());
        Object objC = session.getAttribute("client");
        if (objC != null && objC instanceof GameClient) {
        	GameClient client = (GameClient) objC;
        	client.parse(message.toString());
        }
    }

    @Override
    public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
        Object objC = session.getAttribute("client");
        if (objC != null && objC instanceof GameClient) {
            GameClient client = (GameClient) objC;
            client.timeOut();
        }
    }
    
    @Override
    public void sessionClosed(IoSession session) throws Exception {
        Object objC = session.getAttribute("client");
        if (objC != null && objC instanceof GameClient) {
        	GameClient client = (GameClient) objC;
            client.quit();
        }
        session.removeAttribute("client");
    }

    @Override
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        Object objC = session.getAttribute("client");
        if (objC != null && objC instanceof GameClient) {
        	GameClient client = (GameClient) objC;
            client.quit();
        }
    }
}
